package educationTool.tools;


import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import educationTool.model.Pair;

public class ParserCSV {
	private static ParserCSV instance = null;
	
	private ParserCSV(){}
	
	synchronized public static ParserCSV getInstance() {
		if (instance == null) {
			instance = new ParserCSV();
                }
		return instance;
	}
	
	public List<Pair> parseCSV(String pathDocumentCSV) {		
		List<Pair> listPairs = new LinkedList<Pair>();			
		String[] strMas;

		try {
			BufferedReader br = new BufferedReader(new FileReader(
					pathDocumentCSV));

			strMas = parseLineByLine(br);
			for (int i = 0; i < strMas.length; i++) {
				String[] parametersForPair = parseParametersForPair(strMas[i]);
				Pair pair = constructPair(parametersForPair);
				listPairs.add(pair);
			}			
		}  catch (IOException e) {
			System.out.println("Sorry, was unable to parse this file\n"
                                + "Try to type another path or check if file exists");
		}
		return listPairs;
	}

	private String[] parseLineByLine(BufferedReader br) throws IOException {
		String[] strMas = null;
		List<String> listTemp = new ArrayList<String>();
		String patternForAlternative = "; *"; 
		String patternForAlternativeGroupWhisStar = ";\\s\\*"; 

		String readLine = br.readLine(); // Missing column headers

		try {
			while ((readLine = br.readLine()) != null) {
				// For alternatives
				if (readLine.indexOf(patternForAlternative) != -1) {
					strMas = parseParametersForPair(readLine);
					String[] temp = strMas[0].split(patternForAlternativeGroupWhisStar);
					for (int i = 0; i < temp.length; i++) {
						if (i != 0)
							temp[i] = "\"*" + temp[i]; 
						for (int j = 1; j < strMas.length; j++)
							temp[i] += "\",\"" + strMas[j]; 
						listTemp.add(temp[i]);
					}
				} else {
					listTemp.add(readLine);
				}
			}
			strMas = (String[]) listTemp.toArray(new String[0]);
		} finally {
			br.close();
		}
		return strMas;
	}

	private String[] parseParametersForPair(String strLine) {
		String pattern = "\",\""; 
		String[] tempMas = strLine.split(pattern);

		return tempMas;
	}

	private Pair constructPair(String[] temp) {
		Pair pair = new Pair();
		String[] temaTypeAudGroup = parseTemaTypeAudGroup(temp[0]);

		pair.setNamePair(temaTypeAudGroup[0]);
		pair.setType(temaTypeAudGroup[1]);
		pair.setAuditorium(temaTypeAudGroup[2]);
		pair.setGroup(temaTypeAudGroup[3]);
		pair.setDateBegin(parseDate(temp[1], temp[2]));
		pair.setDateEnd(parseDate(temp[3], temp[4]));

		return pair;
	}

	private String[] parseTemaTypeAudGroup(String str) {
		String[] tempMas = null;
		String tema, type, aud, group = ""; 
		String patternForTema = "(Конс)|(Лк)|(Пз)|(Лб)|(У.Лк)|(ЕкзУ)|(Мод)|(Зал)|(ЕкзП)"; 
		char space = '\u0020';

		tempMas = str.split(patternForTema);
		String[] audGroup = tempMas[1].split(" "); 

		tema = tempMas[0].substring(1).trim(); // Missing "
		
		type = str.substring(tema.length() + 2,
				str.indexOf(space, tema.length()+2));
		
		if (tempMas[1].indexOf('*') != -1) {
			group = tempMas[1].substring(tempMas[1].indexOf('*'),
					tempMas[1].length());
		} else {
			group = audGroup[audGroup.length - 1];
		}
		aud = tempMas[1].substring(0,
				(tempMas[1].length() - group.length() - 1)).trim();	

		return new String[] { tema, type, aud, group };
	}

	private Date parseDate(String date, String time) {
		Date dateTime = null;
		String dateTimeStr = date + time;

		final SimpleDateFormat sdfDate = new SimpleDateFormat(
				"dd.MM.yyyyHH:mm:ss"); 
		final SimpleDateFormat sdfDateFinish = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss"); 

		try {
			String dateTimeStrFinish = sdfDateFinish.format((sdfDate
					.parse(dateTimeStr)));
			dateTime = sdfDateFinish.parse(dateTimeStrFinish);
		} catch (ParseException ex) {
			throw new RuntimeException(ex);
		}
		return dateTime;
	}

}